<?php
/**
 * Service User
 * User: Administrator
 * Date: 2020/2/17 0017
 * Time: 下午 1:29
 */
namespace app\api\service\user;

use app\api\model\user\UserCoupons as UserCouponsModels;
use think\db\exception\ModelNotFoundException;

Class UserCoupons{

    /**
     * 获取用户优惠券列表
     *
     * @return mixed
     */
    public function lists(  )
    {
        return UserCouponsModels::with(['coupons'=>function($query){
            $query->append(['start_date_text','end_date_text','type_text']);
        }])->select();
    }

    /**
     * 获取可用优惠券列表
     * @param int $type
     * @param float $price
     * @throws ModelNotFoundException
     * @return mixed
     */
    public function available(int $type, float $price)
    {
        $userCoupons = UserCouponsModels::field('coupons.price,coupons.id,coupons.start_date,coupons.end_date,coupons.available,coupons.type')
            ->leftJoin('coupons', 'cid = coupons.id')
            ->where('status', 0)
            ->where('(find_in_set(0, coupons.type) or find_in_set('.$type.', type))')
            ->where('coupons.start_date', '<=', date("Y-m-d", time()))
            ->where('coupons.end_date', '>=', date("Y-m-d", time()))
            ->where('coupons.available', '<=', $price)
            ->select();
        if ( $userCoupons->isEmpty() === true ) {
            throw new ModelNotFoundException('您访问的资源不存在');
        }
        $config = config('field.coupons.type');
        foreach ( $userCoupons as $key => $_userCoupons ) {
            $userCoupons[$key]['type_text'] = implode(',', array_map(function($v)use($config){
                return $config[$v];
            }, explode(',', $_userCoupons['type'])));
            $userCoupons[$key]['start_date_text'] = date("Y.m.d", strtotime($_userCoupons['start_date']));
            $userCoupons[$key]['end_date_text'] = date("Y.m.d", strtotime($_userCoupons['end_date']));
        }
        return $userCoupons;
    }

}